import { Inject, Injectable } from '@nestjs/common';
import Redis from 'ioredis';
import {
  CacheEnum,
  REDIS_CLIENT,
} from '../../../common/constants/redis.constant';
import {
  VerifyMethod,
  VerifyType,
} from '../../../common/constants/user.constant';

@Injectable()
export class RedisService {
  @Inject(REDIS_CLIENT)
  private readonly redis: Redis;

  async set(
    key: string,
    value: string | Buffer | number,
    type: any = 'EX',
    expire = 60 * 5,
  ) {
    return await this.redis.set(key, value, type, expire);
  }

  async get(key: string) {
    return await this.redis.get(key);
  }

  async del(key: string) {
    return await this.redis.del(key);
  }

  async exist(key: string) {
    return await this.redis.exists(key);
  }

  async ttl(key: string) {
    return await this.redis.ttl(key);
  }

  /**
   * 根据key开头删除redis数据
   * @param prefix key开头
   */
  async deleteKeysByPrefix(prefix: string): Promise<void> {
    let cursor = '0';
    const keys = [];
    do {
      const result = await this.redis.scan(
        cursor,
        'MATCH',
        prefix + '*',
        'COUNT',
        100,
      );
      cursor = result[0];
      keys.push(...result[1]);
    } while (cursor !== '0');
    if (keys.length) {
      await this.redis.del(keys);
    }
  }
}

/**
 * 生成文本验证码缓存key
 * @param VerifyMethod 验证方式
 * @param VerifyType 验证类型
 * @param account 绑定账号
 * @returns
 */
export const generateVerfyCodeKey = (
  method: VerifyMethod,
  type: VerifyType,
  account: string,
) => {
  return `${CacheEnum.VERIFY_CODE}:${method}:${type}:${account}`;
};

/**
 * 生成图形验证码缓存key
 * @param code 验证码
 * @returns
 */
export const generateCaptchaKey = (code: string) => {
  return `${CacheEnum.SVG_CAPTHA}:${code}`;
};

/**
 * 生成记录IP登录异常次数key
 * @param ip
 * @returns
 */
export const generateLoginExceptionKey = (ip: string) => {
  return `${CacheEnum.LOGIN_EXCEPTION}:${ip}`;
};
